package com.itheima.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.service.OrderService;
import constant.MessageConstant;
import entity.Result;
import org.apache.xmlbeans.impl.jam.mutable.MElement;
import org.aspectj.bridge.Message;
import org.springframework.beans.factory.annotation.Autowired;
import pojo.Member;
import pojo.Order;
import pojo.OrderSetting;
import utils.DateUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService{
    
    @Autowired
    private OrderDao orderDao;
    
    @Autowired
    private OrderSettingDao orderSettingDao;
    
    @Autowired
    private MemberDao memberDao;
    
    //进行预约
    @Override
    public Result order(Map map) throws Exception {
        String orderDate = (String) map.get("orderDate");
        System.out.println("orderDate ：" + orderDate );
        if(orderDate == null){
            return new Result(false,MessageConstant.SELECTED_DATE_NULL);
        }
        Date date = DateUtils.parseString2Date(orderDate);
        System.out.println("用户选择日期：" + date);
        //判断用户所选日期是否在预约设置范围内
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        System.out.println("findByOrderDate:" + orderSetting.getOrderDate());
        if(orderSetting == null){
            //所选日期不能进行体检预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        
        //判断预约人数是否已满
        long number = orderSettingDao.findNumberByDate(date);//可预约人数
        long reservationsByDate = orderSettingDao.findReservationsByDate(date);//已预约人数
        if(reservationsByDate >= number){
            //预约已满
            return new Result(false,MessageConstant.ORDER_FULL);
        }
        
        //判断是否为重复预约(同一个用户，同一天，同一个套餐)
        //先查找用户(会员)，用户不存在-->添加此会员以及预约 ， 用户存在-->查看是否重复预约，不重复则进行预约
        String phoneNumber = (String) map.get("telephone");
        System.out.println("电话号码：" + phoneNumber);
        Member member = memberDao.findMemberByPhoneNumber(phoneNumber);
        
        String s = (String) map.get("setmealId");
        Integer setmeal_id = Integer.valueOf(s);
      
        //Integer setmeal_id = map.get("setmealId");//java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
        //会员已存在
        if(member != null){
            System.out.println("会员已存在");
            //查询此会员是否有重复预约信息
            Integer member_id = member.getId();
            Order order = new Order(member_id,date,null,null,setmeal_id);
            List<Order> list = orderDao.findSameOrder(order);
            if(list != null && list.size() > 0){
                //预约重复
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }
        //会员不存在
        if(member == null){
            System.out.println("会员不存在");
            //当前用户还不是会员，添加到会员表
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(phoneNumber);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());//注册时间
            try{
                System.out.println("开始添加会员");
                memberDao.add(member);//使用了selectKey可以member.getId()获取到id
                System.out.println("会员添加成功");
                System.out.println("会员id:" + member.getId());
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,MessageConstant.ADD_MEMBER_FAIL);
            }
        }
        System.out.println("添加体检预约");
        //添加体检预约
        String orderType = (String) map.get("orderType");
        String orderStatus = Order.ORDERSTATUS_NO;//未到诊
        try{
            Order order = new Order(member.getId(),date,orderType,orderStatus,setmeal_id);
            orderDao.add(order);
            
            //更新预约设置里的已预约人数
            orderSettingDao.updateReservations(orderSetting);
      
            //预约成功
            return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
        }catch (Exception e){
            //预约失败，或者预约设置中已预约人数更新失败
            return new Result(true,MessageConstant.ORDER_FAIL + "或者" + MessageConstant.ORDERSETTING_FAILUPDATE);
        }
    }
    
    //查询的预约信息除了预约信息也包含会员信息和套餐信息
    @Override
    public Map findOrderWithMemberAndSetmeal(Integer orderId) throws Exception {
        /**
         * controller层：
         *  Map map = orderService.findOrderWithMemberAndSetmeal(orderId);
         *  System.out.println(map.get("orderDate") );
         *  //打印2022-09-13但是前端显示2022-09-13 00:00:00,解决：service层把它转为String再放进map
         */
        Map map = orderDao.findOrderWithMemberAndSetmeal(orderId);
        Date date = (Date) map.get("orderDate");
        String strDate = DateUtils.parseDate2String(date);
        map.put("orderDate",strDate);
        return map;
    }
    
}
